package  com.hx.base.servlet.velocity;
import java.io.OutputStreamWriter;
import java.io.Writer;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.VelocityResult;
import org.apache.struts2.views.JspSupportServlet;
import org.apache.struts2.views.velocity.VelocityManager;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;

public class VelocityFixResult extends VelocityResult{

    private static final long serialVersionUID = 7268830767762559424L;
    private static final Logger LOG = LoggerFactory.getLogger(VelocityFixResult.class);
    private static final String IS_BACKPAGE = "is_backpage";

    private VelocityManager velocityManager;

    public VelocityFixResult() {
        super();
    }

    public VelocityFixResult(String location) {
        super(location);
    }
   
    @Inject
    public void setVelocityManager(VelocityManager mgr) {
        this.velocityManager = mgr;
    }
    
	@Override
	public void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    	
    	 ValueStack stack = ActionContext.getContext().getValueStack();

         HttpServletRequest request = ServletActionContext.getRequest();
         HttpServletResponse response = ServletActionContext.getResponse();
         JspFactory jspFactory = null;
         ServletContext servletContext = ServletActionContext.getServletContext();
         Servlet servlet = JspSupportServlet.jspSupportServlet;

         velocityManager.init(servletContext);

         boolean usedJspFactory = false;
         PageContext pageContext = (PageContext) ActionContext.getContext().get(ServletActionContext.PAGE_CONTEXT);

         if (pageContext == null && servlet != null) {
             jspFactory = JspFactory.getDefaultFactory();
             pageContext = jspFactory.getPageContext(servlet, request, response, null, true, 8192, true);
             ActionContext.getContext().put(ServletActionContext.PAGE_CONTEXT, pageContext);
             usedJspFactory = true;
         }

         try {
             String encoding = getEncoding(finalLocation);
             String contentType = getContentType(finalLocation);

             if (encoding != null) {
                 contentType = contentType + ";charset=" + encoding;
             }

             //VelocityEngine engine = velocityManager.getVelocityEngine();
             //String layoutDir = (String)engine.getProperty(PROPERTY_LAYOUT_DIR);
             Template t = getTemplate(stack, velocityManager.getVelocityEngine(), invocation, finalLocation, encoding);
             //进入action之后,从stack中获取值,存在则插入request中
             String backValue = (String)stack.findValue(IS_BACKPAGE);
             if( backValue != null){
                 request.setAttribute(IS_BACKPAGE, backValue);
             }
            
            LOG.debug("===redirect==" + "is_backpage==>:stack value[" + backValue + "] == request attribute["+ request.getAttribute(IS_BACKPAGE) + "]======");
            
            Context context = createContext(velocityManager, stack, request, response, finalLocation);
            //layout合并，可以将页面执行结果写入到字符串缓存中
 			//StringWriter sw = new StringWriter();
// 			t.merge(context, sw);            
// 			context.put("KEY_SCREEN_CONTENT", sw.toString());
// 			Object obj = context.get("KEY_LAYOUT");
//			String layout = (obj == null) ? null : obj.toString();
// 			Template layout_vm = getTemplate(stack, velocityManager.getVelocityEngine(), 
//					invocation, layout, encoding);
// 			layout_vm.merge(context, writer);
// 			
             Writer writer = new OutputStreamWriter(response.getOutputStream(), encoding);


             response.setContentType(contentType);

             t.merge(context, writer);

             // always flush the writer (we used to only flush it if this was a jspWriter, but someone asked
             // to do it all the time (WW-829). Since Velocity support is being deprecated, we'll oblige :)
             writer.flush();
         } catch (Exception e) {
        	 e.printStackTrace();
             LOG.error("Unable to render Velocity Template, '" + finalLocation + "'", e);
             throw e;
         } finally {
             if (usedJspFactory) {
                 jspFactory.releasePageContext(pageContext);
             }
         }

         return;
  }
	



}